<?php

namespace App\Http\Middleware;

use App\Helpers\LogHelper;
use App\Helpers\MvcHelper;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Closure;
use Illuminate\Http\Response;

/**
 * 记录接口的请求日志
 * Class RunLogMiddleware
 *
 * @package App\Http\Middleware
 */
class RunLogMiddleware
{

	/**
	 * 获取请求参数
	 *
	 * @return array
	 */
	public function getRequestLog(): array
	{
		return MvcHelper::makeRequestParams();
	}


	/**
	 * 获取响应内容
	 *
	 * @param JsonResponse|Response $response
	 *
	 * @return array | null
	 */
	public function getResponseLog($response): ?array
	{
		return json_decode($response->content(), true);
	}


	public function handle(Request $request, Closure $next)
	{
		$start    = microtime(true);
		$response = $next($request);

		// 日志打开或者特殊的记录日志的账号
		if (env("APP_LOG_OPEN", false)) {
			$end  = microtime(true);
			$mark = 'api_run_log';
			$info = [
				"runtime"  => round(($end - $start), 4),
				"path"     => $request->path(),
				"method"   => $request->method(),
				"request"  => $this->getRequestLog(),
				"response" => $this->getResponseLog($response),
				'srvIp'      => ($_SERVER['SERVER_ADDR'] ?? ''),   // 机器ID:本机ID
				'ip'         => ip($_SERVER), // 请求IP
				"logId"    => NEO_LOGGER_ID,
			];

			LogHelper::info($mark, $info);
		}

		return $response;
	}
}